package com.scm.property;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;


public class FileProperties {
	
	static final Logger log = Logger.getLogger(FileProperties.class); 
	
	private String FILENAME = null;
	private final String VA = "SCM_HOME";
	private Properties properties;
   
	public FileProperties(String fileProperties){
		FILENAME = fileProperties;
		loadProperties(FILENAME);
	}
	
	public Properties getPropertiesObject(){
		return properties;
	}
	
	public String getProperties(String property){
		if(properties == null)
			loadProperties(FILENAME);
		String file = properties.getProperty(property);
		
		if(file == null)
			log.warn("Property "+property+" is NULL!");
		else if(file.isEmpty())
			log.warn("Property "+property+" is EMPTY!");
		
		return file;
	}

	private void loadProperties(String fileName){
		properties = new Properties();
		try {
		InputStream  input = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		if(input!=null)
			properties.load(input);
		else{
	    	
			File propertiesFile = new File(System.getenv(VA),fileName);
            FileInputStream in;
				in = new FileInputStream(propertiesFile); 
				properties.load(in);
				in.close();
	    }
		} catch (FileNotFoundException e) {
			log.error("FilePropertiesNotFoundException: Va:"+System.getenv(VA)+","+fileName);
			log.error("FilePropertiesNotFoundException: "+e);
		} 
	    catch (IOException e) {
	    	log.error("FilePropertiesIOException: Va:"+System.getenv(VA)+","+fileName);
	    	log.error("FilePropertiesIOException: "+e);
	    } 
	}
	
	public String getSystemVA(){
		String dirVa =  System.getenv(VA);
		
		if(dirVa == null)
			log.warn("Variabile d'ambiente "+dirVa+" is NULL!");
		else if(dirVa.isEmpty())
			log.warn("Variabile d'ambiente "+dirVa+" is VUOTA!");
		
		return dirVa;
	}

}
